
#include "Zero.h"
#include "APP_Main.h"
#include "apt32f102_syscon.h"
#include "apt32f102_bt.h"


// uint32_t Fan_delay_us = 7900; //0:常开; <8000:最慢; >=8000:常关
uint32_t Fan_delay_us = 7900; //0:常开; <8000:最慢; >=8000:常关
// uint32_t Fan_delay_us = 0; //0:常开; <8000:最慢; >=8000:常关
uint32_t Fan_ZeroCtrl = 0; //控制风扇负载开关
uint32_t Fan_Disable = 0; //控制风扇负载开关 使能, 负载检测使用


void Zero_FanCtrl(uint8_t param)
{
	if(Fan_Disable > 0) return;
	if((Fan_ZeroCtrl == 0) || (param == 0))
	{
		ExhaustFanClose;
	}
	else
	{
		ExhaustFanOpen;
	}
}

//IO口触发中断: 下降沿中断
//在RAM中运行代码 加快响应速度
void Zero_handler()
{
    uint32_t io_Level = 0;
    uint32_t temp = 0;
    
    if(ReadIO_CrossZero() == 0)
    {
        if(Fan_delay_us == 0)
        { //常开
            // ExhaustFanOpen;
			Zero_FanCtrl(1);	
        }
        else if(Fan_delay_us >= 8000)
        { //常关: 停止
            // ExhaustFanClose;
			Zero_FanCtrl(0);	
        } 
        else
        { //1 ~ 9
            // ExhaustFanClose;
			Zero_FanCtrl(0);	

            //理论数据: 50Hz 可调范围[0, 8ms]; 60Hz 可调范围[0, ms]
            //  为了兼容50Hz跟60Hz -> 取可调范围[0ms, ms]
            //实际情况: IO下降沿触发占用1ms; 无效时间占用1ms 可调范围[0,8ms]
            //    1ms转速最快, 8ms转速最慢(几乎无风,但马达会旋转, 也不会发烫)
            //注意: 可控硅输出光耦必须是不带过零的双向可控硅MOC3023

            //定时器延迟执行 打开风扇负载
            BT_Period_CMP_Write(BT0, Fan_delay_us,1); //周期时间1000us, 占空比1/1000
            BT_Start(BT0);
        }
    }
}

void Zero_Init()
{
    GPIO_Init(GPIOA0,CrossZero,Intput);

    GPIO_IntGroup_Set(GPIOA, CrossZero, Selete_EXI_PIN11); //EXI3 set PA11
    GPIOA0_EXI_Init(CrossZero);
    EXTI_trigger_CMD(ENABLE,EXI_PIN11,_EXIFT); //_EXIFT下降沿触发, _EXIRT 上升沿触发
    EXTI_interrupt_CMD(ENABLE,EXI_PIN11);
    GPIO_EXTI_interrupt(GPIOA0,0x800);
    EXI4_Int_Enable(); //使能 GPIO 口外部中断
    // EXI3_WakeUp_Enable();   

    BT_CONFIG();
}

//IO口触发中断: 下降沿中断
void EXI10to15IntHandler(void) 
{
    // ISR content ...
	if ((SYSCON->EXIRS&EXI_PIN10)==EXI_PIN10) 
	{
		SYSCON->EXICR = EXI_PIN10;
	} 
	else if ((SYSCON->EXIRS&EXI_PIN11)==EXI_PIN11) 
	{
		SYSCON->EXICR = EXI_PIN11;

		//过零信号触发
        Zero_handler();
	} 
	else if ((SYSCON->EXIRS&EXI_PIN12)==EXI_PIN12) 
	{
		SYSCON->EXICR = EXI_PIN12;
	} 
	else if ((SYSCON->EXIRS&EXI_PIN13)==EXI_PIN13) 
	{
		SYSCON->EXICR = EXI_PIN13;
	}
	else if ((SYSCON->EXIRS&EXI_PIN14)==EXI_PIN14) 
	{
		SYSCON->EXICR = EXI_PIN14;
	}
	else if ((SYSCON->EXIRS&EXI_PIN15)==EXI_PIN15) 
	{
		SYSCON->EXICR = EXI_PIN15;
	}
}

void BT0IntHandler(void) 
{
	if((BT0->MISR&BT_PEND)==BT_PEND)
	{
		BT0->ICR = BT_PEND;

	    BT_Stop(BT0);
        // ExhaustFanOpen;
		Zero_FanCtrl(1);	
	} 
	else if((BT0->MISR&BT_CMP)==BT_CMP)
	{ //周期定时中断
		BT0->ICR = BT_CMP;
	}
	else if((BT0->MISR&BT_OVF)==BT_OVF)
	{
		BT0->ICR = BT_OVF;
	} 
	else if((BT0->MISR&BT_EVTRG)==BT_EVTRG)
	{
		BT0->ICR = BT_EVTRG;
	} 
}
